<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>提取图片主颜色</title>
  <style type="text/css">
    * {
      margin: 0;
      padding: 0;
    }

    body {
      overflow: hidden;
    }

    #wrapper {
      width: 100%;
      height: 100vh;
      position: relative;
    }

    #firCan {
      display: block;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border-radius: 10px;
      box-shadow: 4px 4px 20px #888888;
      ;
    }

    #box {
      height: 100%;
      /* filter: blur(100px); */
    }

    #btn {
      position: absolute;
      top: 10px;
      left: 50%;
      transform: translateX(-50%);
    }
  </style>
</head>

<body>
  <div id="wrapper">
    <div id="box"></div>
    <canvas id="firCan" width="1000" height="625">
      您的浏览器版本过低, 不支持Canvas, 请升级!
    </canvas>
    <button id="btn">切换图片</button>
  </div>

</body>
<script type="text/javascript">
  let box = document.getElementById("box");
  let btn = document.getElementById("btn");
  // 1, 获取Canvas
  var firCan = document.getElementById("firCan");
  // 2, 获取 2d渲染上下文
  var context = firCan.getContext('2d');
  // 3, 加载图片
  // 创建 img对象
  var imgObj = new Image();
  // 设置 src
  let imgIndex = 0;
  const imgArr = ['img/banner3.png', 'img/1.jpg'];
  imgObj.src = imgArr[imgIndex];
  btn.onclick = function () {
    imgIndex++;
    if (imgIndex >= imgArr.length) {
      imgIndex = 0;
    }
    imgObj.src = imgArr[imgIndex];
  }

  // 图片加载完毕
  imgObj.onload = function () {
    // 图片绘制到 canvas: drawImage()
    context.drawImage(imgObj, 0, 0, 1280, 800, 0, 0, 1000, 625);
    var getImageData = context.getImageData(0, 0, firCan.width, firCan.height);
    console.log(getImageData);
    let colorList = getCountsArr(getImageData.data)

    let arr = [];
    // 对colorList进行排序
    for (let prop in colorList) {
      arr.push({
        // 如果只获取rgb,则为`rgb(${prop})`
        color: `rgba(${prop})`,
        count: colorList[prop],
      });
    }
    // 数组排序(降序)
    arr.sort((a, b) => {
      return b.count - a.count;
    });

    // console.log("arr", arr);

    // 排名第一的颜色就是主色彩
    console.log('主色彩：', arr[0].color);

    const mainColor = arr[0].color

    box.style.background = mainColor;
  }

  // 对图片的颜色值进行分组，并统计每种颜色出现的次数
  function getCountsArr(pixelData) {
    let colorList = [];
    let rgba = [];
    let rgbaStr = "";
    // 分组循环
    for (let i = 0; i < pixelData.length; i += 4) {
      rgba[0] = pixelData[i];
      rgba[1] = pixelData[i + 1];
      rgba[2] = pixelData[i + 2];
      rgba[3] = pixelData[i + 3];

      if (rgba.indexOf(undefined) !== -1 || pixelData[i + 3] === 0) {
        continue;
      }
      // console.log("rgba", rgba);
      rgbaStr = rgba.join(",");
      if (rgbaStr in colorList) {
        ++colorList[rgbaStr];
      } else {
        colorList[rgbaStr] = 1;
      }
    }
    // console.log("colorList", colorList);

    return colorList;
  }

</script>

</html>